package com.hingsmy.pma.controllers;

import com.hingsmy.pma.dao.StudentRepository;
import com.hingsmy.pma.entities.Student;
import com.hingsmy.pma.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.List;

@Controller
//导航到http://localhost:8080/students
@RequestMapping("students")
public class StudentController {

    @Autowired
    StudentService studentService;

    @GetMapping
    public String displayStudents(Model model) {
        List<Student> students = studentService.getAll();
        model.addAttribute("students", students);
        return "students/list-students";
    }

    // 导航到http://localhost:8080/students/new
    @GetMapping("/new")
    public String displayStudentForm(Model model) {
        Student aStudent = new Student();
        model.addAttribute("student", aStudent);
        return "students/new-student";
    }

    // 导航到http://localhost:8080/students/save
    @PostMapping("/save")
    public String createProject(Model model, @Valid Student student, Errors errors) {
        //处理保存到数据库的行为
        if (errors.hasErrors())return "students/new-student";
        studentService.save(student);
        return "redirect:/students";
    }

    @RequestMapping("/update")
    public String displayStudentUpdateForm(@RequestParam("id") long theid, Model model) {
        Student student = studentService.findbystudentId(theid);
        model.addAttribute("student", student);
        return "students/new-student";
    }

    @RequestMapping("/delete")
    public String deleteStudent(@RequestParam("id") long theid, Model model, Student student) {
        Student students = studentService.findbystudentId(theid);
        studentService.delete(student);
        return "students/new-student";

    }
}
